package com.xiupopo.shopping.view.bean;

<#foreach field in pojo.getAllPropertiesIterator()>
<#if pojo.getJavaTypeName(field, jdk5).equals("Set<String>")>
	<#assign hasSet = true >
<#else>
	<#assign hasSet = false >
</#if>
</#foreach>

import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xiupopo.shopping.model.businessobject.${pojo.getDeclarationName()};
import com.xiupopo.shopping.model.service.${pojo.getDeclarationName()}Service;
import com.xiupopo.shopping.model.service.impl.${pojo.getDeclarationName()}ServiceImpl;

<#if hasSet>
import com.xiupopo.shopping.model.businessobject.Category;
import com.xiupopo.shopping.model.service.CategoryService;
import com.xiupopo.shopping.model.service.impl.CategoryServiceImpl;

import java.util.ArrayList;
import java.util.Iterator;
</#if>

/**
 * ${pojo.getDeclarationName()} backing bean.
 */
public class ${pojo.getDeclarationName()}Bean {
	Logger logger = LoggerFactory.getLogger(${pojo.getDeclarationName()}Bean.class);

	private ${pojo.getDeclarationName()} ${pojo.getDeclarationName()?uncap_first};
	private List<${pojo.getDeclarationName()}> ${pojo.getDeclarationName()?uncap_first}List;

<#if hasSet>
	// for category
	private List<Category> categoryAllList;
	private List<Category> categoryHaveList;
	private List<Category> categoryNoneList;
	private boolean categoryHaveListEmpty;
	private boolean categoryNoneListEmpty;
	

	private void buildDataAfterRead()
	{
		logger.debug("buildDataAfterRead() is invoked");
		categoryHaveList = new ArrayList<Category>();
		categoryNoneList = new ArrayList<Category>();
		CategoryService service = new CategoryServiceImpl();
		categoryAllList = service.getCategorys();

		for( Iterator<Category> itr = categoryAllList.iterator(); itr.hasNext(); )
		{
			Category cat = itr.next();
			if( ${pojo.getDeclarationName()?uncap_first}.getCategoryIds().contains(""+cat.getId()) ) 
			{
				categoryHaveList.add(cat);
			}
			else
			{
				categoryNoneList.add(cat);
			}
		}
		categoryHaveListEmpty = categoryHaveList.isEmpty();
		categoryNoneListEmpty = categoryNoneList.isEmpty();
	}
	private void buildDataBeforeStore()
	{
		logger.debug("buildDataBeforeStore() is invoked");
		product.getCategoryIds().clear();
		for( Iterator<Category> itr = categoryHaveList.iterator(); itr.hasNext(); )
		{
			Category cat = itr.next();
			${pojo.getDeclarationName()?uncap_first}.getCategoryIds().add(""+cat.getId());
		}
	}

	public String addCategoryAction()
	{
		logger.debug("addCategoryAction is invoked");
		FacesContext context = FacesContext.getCurrentInstance();
		String paramValue = (String)context.getExternalContext()
			.getRequestParameterMap().get("category_id");
		${pojo.getDeclarationName()?uncap_first}.getCategoryIds().add(paramValue);
		buildDataAfterRead();
		return NavigationResults.SUCCESS;
	}
	public String removeCategoryAction()
	{
		logger.debug("removeCategoryAction is invoked");
		FacesContext context = FacesContext.getCurrentInstance();
		String paramValue = (String)context.getExternalContext()
			.getRequestParameterMap().get("category_id");
		${pojo.getDeclarationName()?uncap_first}.getCategoryIds().remove(paramValue);
		buildDataAfterRead();
		return NavigationResults.SUCCESS;
	}

</#if>

	public ${pojo.getDeclarationName()}Bean() 
	{
		logger.debug("${pojo.getDeclarationName()}Bean is created");
		${pojo.getDeclarationName()?uncap_first} = new ${pojo.getDeclarationName()}();
<#if hasSet>
		buildDataAfterRead();
</#if>
	}
	public String newAction() 
	{
		logger.debug("createAction is invoked");
		${pojo.getDeclarationName()?uncap_first} = new ${pojo.getDeclarationName()}();
<#if hasSet>
		buildDataAfterRead();
</#if>
		return NavigationResults.SUCCESS;
	}
	/**
	 * Backing bean action to create a new ${pojo.getDeclarationName()?uncap_first}.
	 * 
	 * @return the navigation result
	 */
	public String createAction() 
	{
		logger.debug("createAction is invoked");
		try 
		{
<#if hasSet>
			buildDataBeforeStore();
</#if>
			${pojo.getDeclarationName()}Service service = new ${pojo.getDeclarationName()}ServiceImpl();
			service.create${pojo.getDeclarationName()}(${pojo.getDeclarationName()?uncap_first});
			${pojo.getDeclarationName()?uncap_first}List = service.get${pojo.getDeclarationName()}s();
<#if !pojo.generateAnnIdGenerator().equals("") >
			logger.debug("new ${pojo.getDeclarationName()} created. id = " + ${pojo.getDeclarationName()?uncap_first}.getId());
</#if>
		} 
		catch( ConstraintViolationException e)
		{
			String msg = "Could not create ${pojo.getDeclarationName()?uncap_first} due to contraint violation. ";
			logger.debug(msg, e);
			FacesContext.getCurrentInstance().addMessage(
					"${pojo.getDeclarationName()?uncap_first}_create",
					new FacesMessage("Duplicate entry found. Please try again with different value") );
			return NavigationResults.FAILURE;
		}
		catch (Exception e) 
		{
			String msg = "Could not create ${pojo.getDeclarationName()?uncap_first}";
			logger.error(msg, e);
			//FacesUtils.addErrorMessage(msg + ": Internal Error.");
			return NavigationResults.FAILURE;
		}
<#if !pojo.generateAnnIdGenerator().equals("") >
		String msg = "${pojo.getDeclarationName()} with id of " + ${pojo.getDeclarationName()?uncap_first}.getId() + " was created successfully.";
		logger.debug(msg);
</#if>
		//FacesUtils.addInfoMessage(msg);
		return NavigationResults.SUCCESS;
	}

	/**
	 * Backing bean action to read ${pojo.getDeclarationName()?uncap_first}.
	 * 
	 * @return the navigation result
	 */
	@SuppressWarnings("unchecked")
	public String readAction() {
		logger.debug("readAction is invoked");
		FacesContext context = FacesContext.getCurrentInstance();
		String paramValue = (String)context.getExternalContext()
			.getRequestParameterMap().get("${pojo.getDeclarationName()?uncap_first}_id");
		try {
			${pojo.getDeclarationName()}Service ps = new ${pojo.getDeclarationName()}ServiceImpl();
			${pojo.getDeclarationName()?uncap_first} = ps.read${pojo.getDeclarationName()}(Long.valueOf(paramValue));
<#if hasSet>
			buildDataAfterRead();
</#if>
<#if !pojo.generateAnnIdGenerator().equals("") >
			logger.debug("${pojo.getDeclarationName()?uncap_first}Id = " + ${pojo.getDeclarationName()?uncap_first}.getId() + " was read.");
</#if>
		} catch (Exception e) {
			String msg = "Could not read ${pojo.getDeclarationName()?uncap_first}. id:" + paramValue;
			logger.error(msg, e);
			return NavigationResults.FAILURE;
		}
<#if !pojo.generateAnnIdGenerator().equals("") >
		String msg = "${pojo.getDeclarationName()} with id of " + this.${pojo.getDeclarationName()?uncap_first}.getId() + " was read successfully.";
		logger.debug(msg);
</#if>
		return NavigationResults.SUCCESS;
	}
	/**
	 * Backing bean action to update ${pojo.getDeclarationName()?uncap_first}.
	 * 
	 * @return the navigation result
	 */
	public String updateAction() {
		logger.debug("updateAction is invoked");
		try {
<#if hasSet>
			buildDataBeforeStore();
</#if>
			${pojo.getDeclarationName()}Service service = new ${pojo.getDeclarationName()}ServiceImpl();
			service.update${pojo.getDeclarationName()}(this.${pojo.getDeclarationName()?uncap_first});
			${pojo.getDeclarationName()?uncap_first}List = service.get${pojo.getDeclarationName()}s();
<#if !pojo.generateAnnIdGenerator().equals("") >
			logger.debug("${pojo.getDeclarationName()?uncap_first}Id = " + ${pojo.getDeclarationName()?uncap_first}.getId() + " was updated.");
</#if>
			//remove the ${pojo.getDeclarationName()?uncap_first}List inside the cache
			//FacesUtils.resetManagedBean(BeanNames.PRODUCT_LIST_BEAN);
		}
		catch( ConstraintViolationException e)
		{
			String msg = "Could not create ${pojo.getDeclarationName()?uncap_first} due to contraint violation. ";
			logger.debug(msg, e);
			FacesContext.getCurrentInstance().addMessage(
					"${pojo.getDeclarationName()?uncap_first}_update",
					new FacesMessage("Duplicate entry found. Please try again with different value") );
			return NavigationResults.FAILURE;
		} 
		catch (Exception e) 
		{
			String msg = "Could not update ${pojo.getDeclarationName()?uncap_first}";
			logger.error(msg, e);
			//FacesUtils.addErrorMessage(msg + ": Internal Error.");
			return NavigationResults.FAILURE;
		}
<#if !pojo.generateAnnIdGenerator().equals("") >
		String msg = "${pojo.getDeclarationName()} with id of " + ${pojo.getDeclarationName()?uncap_first}.getId() + " was updated successfully.";
		logger.debug(msg);
</#if>
		//FacesUtils.addInfoMessage(msg);
		return NavigationResults.SUCCESS;
	}
	
	
	/**
	 * Backing bean action to delete ${pojo.getDeclarationName()?uncap_first}.
	 * 
	 * @return the navigation result
	 */
	@SuppressWarnings("unchecked")
	public String deleteAction() {
		logger.debug("deleteAction is invoked");
		FacesContext context = FacesContext.getCurrentInstance();
		String paramValue = (String)context.getExternalContext()
			.getRequestParameterMap().get("${pojo.getDeclarationName()?uncap_first}_id");
		try {
			${pojo.getDeclarationName()}Service service = new ${pojo.getDeclarationName()}ServiceImpl();
			${pojo.getDeclarationName()} value = service.read${pojo.getDeclarationName()}(Long.valueOf(paramValue));
			service.delete${pojo.getDeclarationName()}( value );
			${pojo.getDeclarationName()?uncap_first}List = service.get${pojo.getDeclarationName()}s();
			logger.debug("${pojo.getDeclarationName()?uncap_first}Id = " + paramValue + " was deleted.");
		} catch (Exception e) {
			String msg = "Could not delete ${pojo.getDeclarationName()?uncap_first}. id:" + paramValue;
			logger.error(msg, e);
			return NavigationResults.FAILURE;
		}
		
		String msg = "${pojo.getDeclarationName()} with id of " + paramValue  + " was deleted successfully.";
		logger.debug(msg);
		return NavigationResults.SUCCESS;
	}

	public String loadList() {
		logger.debug("${pojo.getDeclarationName()}Bean() is invoked");
		try {
			${pojo.getDeclarationName()}Service service = new ${pojo.getDeclarationName()}ServiceImpl();
			${pojo.getDeclarationName()?uncap_first}List = service.get${pojo.getDeclarationName()}s();
			logger.debug("${pojo.getDeclarationName()?uncap_first}s loaded. total size:" + ${pojo.getDeclarationName()?uncap_first}List.size());
		} catch (Exception e) {
			String msg = "Could not load ${pojo.getDeclarationName()?uncap_first}s. ";
			logger.error(msg, e);
			return NavigationResults.FAILURE;
		}
		return NavigationResults.SUCCESS;
	}
	
	public ${pojo.getDeclarationName()} get${pojo.getDeclarationName()}() {
		return ${pojo.getDeclarationName()?uncap_first};
	}
	public void set${pojo.getDeclarationName()}(${pojo.getDeclarationName()} ${pojo.getDeclarationName()?uncap_first}) {
		this.${pojo.getDeclarationName()?uncap_first} = ${pojo.getDeclarationName()?uncap_first};
	}
	public List<${pojo.getDeclarationName()}> get${pojo.getDeclarationName()}List() {
		return ${pojo.getDeclarationName()?uncap_first}List;
	}
	public void set${pojo.getDeclarationName()}List(List<${pojo.getDeclarationName()}> ${pojo.getDeclarationName()?uncap_first}List) {
		this.${pojo.getDeclarationName()?uncap_first}List = ${pojo.getDeclarationName()?uncap_first}List;
	}
	
<#if !pojo.generateAnnIdGenerator().equals("") >
	public List<Category> getCategoryHaveList() {
		return categoryHaveList;
	}
	public void setCategoryHaveList(List<Category> categoryHaveList) {
		this.categoryHaveList = categoryHaveList;
	}
	public List<Category> getCategoryNoneList() {
		return categoryNoneList;
	}
	public void setCategoryNoneList(List<Category> categoryNoneList) {
		this.categoryNoneList = categoryNoneList;
	}
	public boolean isCategoryHaveListEmpty() {
		return categoryHaveListEmpty;
	}
	public void setCategoryHaveListEmpty(boolean categoryHaveListEmpty) {
		this.categoryHaveListEmpty = categoryHaveListEmpty;
	}
	public boolean isCategoryNoneListEmpty() {
		return categoryNoneListEmpty;
	}
	public void setCategoryNoneListEmpty(boolean categoryNoneListEmpty) {
		this.categoryNoneListEmpty = categoryNoneListEmpty;
	}
</#if>
}
